/**
 * Created by xiazm on 2023-02-27
 * @param el
 * @returns {number}
 */


// 获取元素的宽度
function outerHeight(el) {
    let height = el.offsetHeight;
    let style = getComputedStyle(el);
    height += parseInt(style.marginTop) + parseInt(style.marginBottom);
    return height;
}
// 获取元素的高度
function outerWidth(el) {
    let width = el.offsetWidth;
    let style = getComputedStyle(el);
    width += parseInt(style.marginLeft) + parseInt(style.marginRight);
    return width;
}
// 拖拽功能
function drag(dragSelector, moveSelector, scopeSelector, _callback) {
    let dragEl = document.querySelector(dragSelector);
    let moveEl = document.querySelector(moveSelector);
    let scopeEl = document.querySelector(scopeSelector);
    if (!dragEl) {
        return false;
    }
    scopeEl = scopeEl? scopeEl:window;
    if (!moveEl) {
        moveEl = dragEl;
    }
    let gapX,gapY;
    let funStart = function(event) {
        selectionEmpty();
        let p = fixedPosition(this);
        gapX=event.clientX-p.left;
        gapY=event.clientY-p.top;
        //注册事件
        document.addEventListener("mousemove",funMove);
        document.addEventListener("mouseup",funStop);
        //拖拽期间禁止iframe接收事件
        document.querySelectorAll('iframe').forEach(function (item) {
            item.style.pointerEvents = 'none';
        });
        return false;
    }
    let funMove = function(e) {
        selectionEmpty();
        let x = e.clientX - gapX;
        let y = e.clientY - gapY;

        let cw=scopeEl.innerWidth - outerWidth(moveEl);
        let ch=scopeEl.innerHeight - outerHeight(moveEl);
        //console.log('范围',cw,ch,'当前',x,y,'元素',outerWidth(moveEl),outerHeight(moveEl));

        if (x < 0) {
            x = 0;
        } else if (x > cw) {
            x = cw;
        }

        if (y < 0) {
            y = 0;
        } else if (y > ch) {
            y = ch;
        }
        //设置css
        moveEl.style.left = x + 'px';
        moveEl.style.top = y + 'px';

        if (_callback) {
            _callback(x, y);
        }

        return false;
    }
    let funStop = function () {
        document.removeEventListener("mousemove",funMove);
        //恢复iframe的事件接收
        document.querySelectorAll('iframe').forEach(function (item) {
            item.style.pointerEvents = 'auto';
        });
    };
    dragEl.addEventListener("mousedown",funStart);
}

/**
 * 取消页面选中的文字以及其他内容
 */
function selectionEmpty() {
    document.selection && document.selection.empty && ( document.selection.empty(), 1)
    || window.getSelection && window.getSelection().removeAllRanges();
}


//获取el相对于窗口的位置
function fixedPosition(el) {
    let x = 0;
    let y = 0;
    while (el) {
        x += el.offsetLeft;
        y += el.offsetTop;
        el = el.offsetParent;
    }
    return {left:x,top:y};
}

export {
    drag,selectionEmpty,fixedPosition
}
